package com.chapter.sample.answer.interview;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@Slf4j
public class LiveController {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 某个用户(userId=12）第一次进入直播间，返回最新的5条弹幕
     *
     * @param roomId
     * @param userId
     * @return
     */
    @RequestMapping("/goRoom")
    public List<Content> goRoom(Integer roomId, Integer userId) {
        List<Content> list = new ArrayList<>();
        String key = Constants.ROOM_KEY + roomId;
        /**
         * 进入房间返回最新的前5条弹幕
         * 对应redis命令,ZREVRANGE room：100 0，4 withscores
         */
        Set<ZSetOperations.TypedTuple<Content>> range = redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, 4);
        for (ZSetOperations.TypedTuple<Content> obj : range) {
            list.add(obj.getValue());
            log.info("首次进房间取最新前5条弹幕content：「{}」,score:「{}」", obj.getValue(), obj.getScore().longValue());
        }
        //user：room：time：12      12就是userID 观众ID
        String userKey = Constants.ROOM_USER_TIME_KEY + userId;
        //把当前时间T,保持到redis,提供下次拉去用，看过的就不再推送
        Long now = System.currentTimeMillis() / 1000;
        redisTemplate.opsForValue().set(userKey, now);
        return list;
    }

    /**
     * 登陆房间后持续观看,定时任务或者XXL-job 客户端间隔5秒来拉去数据
     *
     * @param roomId
     * @param userId
     * @return
     */
    @RequestMapping("/commentList")
    public List<Content> commentList(Integer roomId, Integer userId) {
        List<Content> list = new ArrayList<>();

        String key = Constants.ROOM_KEY + roomId;
        String userKey = Constants.ROOM_USER_TIME_KEY + userId;

        long now = System.currentTimeMillis() / 1000;
        //获取上次的读取时间
        long ago = Long.parseLong(redisTemplate.opsForValue().get(userKey).toString());
        log.info("查找时间范围：「{}」,「{}」", ago, now);

        //获取上次到现在的数据 zrevrange room:100 0 4 withscores
        Set<ZSetOperations.TypedTuple<Content>> range = redisTemplate.opsForZSet().rangeByScoreWithScores(key, ago, now);
        for (ZSetOperations.TypedTuple<Content> obj : range) {
            list.add(obj.getValue());
            log.info("首次进房间取最新前5条弹幕content：「{}」,score:「{}」", obj.getValue(), obj.getScore().longValue());
        }

        //把当前的时间Time，保持到redis,供下次拉去
        now = System.currentTimeMillis() / 1000;
        redisTemplate.opsForValue().set(userKey, now);
        return list;

    }
}
